#include "FilterSTriangle.h"

#include <algorithm>
#include <cmath>

FilterSTriangle::FilterSTriangle(double support) : Filter(support)
{
	max_x_coord = 0.5 + (support - 1.0);
	max_y_coord = 0.5 + (support - 1.0);
	min_x_coord = -0.5 - (support - 1.0);
	min_y_coord = -0.5 - (support - 1.0);
	 
}

FilterSTriangle::~FilterSTriangle()
{}

/*
 * Should return a weight from 0 to 1, where 1 would be the heighest weight. It probably shouldn't be called
 * outside of getWeights
 */
double FilterSTriangle::getWeight(double x, double y, int num_samples) const
{
	//the given coordinates should vary from -0.5 to 0.5 for a single pixel sampler,
	//more for a multi-pixel
	if(x > max_x_coord || y > max_y_coord)
		return 0;
	if(x < min_x_coord || y < min_x_coord)
		return 0;
	double x_dist = std::abs(x) / max_x_coord;
	double y_dist = std::abs(y) / max_y_coord;
	return (std::min((1 - x_dist), (1 - y_dist)));	
}

void FilterSTriangle::getWeights(double* weights, int samples, double* xs, double* ys) const
{
	double total_weights = 0;
	for(int i = 0; i < samples; i++)
	{
		double cur_weight = getWeight(xs[i], ys[i], samples); 
		weights[i] = cur_weight;
		total_weights += cur_weight;
	}
	for(int i = 0; i < samples; i++)
	{
		weights[i] = weights[i] / total_weights;
	}
	
}


